package com.zbkj.service.service.impl;

import com.zbkj.common.constants.Constants;
import com.zbkj.common.exception.CommonException;
import com.zbkj.common.oss.OssClientUtil;
import com.zbkj.common.utils.CommonUtil;
import com.zbkj.common.utils.LocalDateUtil;
import com.zbkj.service.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;

/**
 * @Auther:
 * @Date: 2024/7/7 21:43
 * @Description:
 */
@Slf4j
@Service
public class UploadServiceImpl implements UploadService {

    @Autowired
    private OssClientUtil ossClientUtil;

    @Override
    public String informationUpload(String fileType, MultipartFile multipartFile) {
        try (InputStream in = multipartFile.getInputStream();){
            String originalFileName = multipartFile.getOriginalFilename().replace(String.format(".%s",fileType),"");
            String datePathStr = LocalDateUtil.formater(LocalDateTime.now(),LocalDateUtil.YYYYMMDD);
            String storagePath = String.format("%s/%s/%s_%s.%s", Constants.PROJECT_DOC_PREFIX,datePathStr,originalFileName,CommonUtil.getUuid(),fileType);
            return ossClientUtil.upload(storagePath, in);
        } catch (IOException ioe) {
            log.error("informationUpload-文件读取错误-file:{}-error:",multipartFile.getOriginalFilename(),ioe);
            throw new CommonException("文件读取错误");
        }
    }

    @Override
    public String informatLocalUpload(File localFile, String ossFileName) {
        String datePathStr = LocalDateUtil.formater(LocalDateTime.now(),LocalDateUtil.YYYYMMDD);
        String storagePath = String.format("%s/%s/%s", Constants.PROJECT_DOC_PREFIX,datePathStr,ossFileName);
        return ossClientUtil.upload(storagePath,localFile);
    }

    @Override
    public String inputStreamUpload(String fileType, String docPrefix, InputStream inputStream) {
        String datePathStr = LocalDateUtil.formater(LocalDateTime.now(),LocalDateUtil.YYYYMMDD);
        String storagePath = String.format("%s/%s/%s.%s", docPrefix,datePathStr,CommonUtil.getUuid(),fileType);
        return ossClientUtil.upload(storagePath,inputStream);
    }

}
